import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Navigator, Block, Text, Image} from '@tarojs/components'
import './detail.scss'
import {AtTabs, AtTabsPane, AtButton, AtTag, AtIcon, AtFloatLayout, AtCalendar} from 'taro-ui'
import { user } from '../../utils/user.service'
import { OrderDetail, TicketItem, RebateInfo } from '../../utils/server.interface'
import { http } from '../../utils/http'
import {
  NEW_GET_ORDER_DETAIL,
  NEW_GET_ORDER_TICKET,
  NEW_GET_ORDER_CHECKLOG,
  REBATE_INFO,
  GET_PCODE, GET_IMG,
  LIAN_ORDER_TICKET, BASE_URL
} from '../../constants/api';
import {convert2CamelCase, GetRequest,vcmonitor} from '../../utils/tools';
import {platform} from "../../utils/platform-settting.service";
import {newHttp} from "../../utils/request";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"

interface LogList {
  use_date: string
  check_num: number
}
const goodsType = {
    limit: 'limited',
    ticket: 'scenic',
    hotel: 'hotel',
    toursLine: 'tourist-line',
    product: 'product'
}

export default class Detail extends Component {
  tabs = platform.info.platform_show_fx_code==1?[{title: '订单详情'},{title: '返利信息'},{title: '核验码'}]:[{title: '订单详情'},{title: '返利信息'}]
  state: {
      tabsIndex: number
      orderInfo: OrderDetail | false
      orderTicket: TicketItem[] | false
      rebateInfo: RebateInfo[]
      logList: LogList[]
      goodDetailUrl: string
      qrcodeimg: string
      pcodeimg: string
    canvasId: string
    openGroup: boolean
    assembling_place_list: any
    openAssembling: boolean
    coupon: boolean
    showCalendar: boolean
  } = {
      tabsIndex: 0,
      pcodeimg:'',
      qrcodeimg:'',
      orderInfo: false,
      rebateInfo: [],
      logList:[],
      goodDetailUrl: '',
    canvasId:'qrcodeimg',
    openGroup:false,
    orderTicket: [],
    assembling_place_list:[],
    openAssembling:false,
    coupon:false,
    showCalendar:false
  }
  tabsChange(index) {
      this.setState({tabsIndex: index})
  }
  async componentDidShow(){
    vcmonitor(this)
  }
  async UNSAFE_componentWillMount() {
    if(process.env.TARO_ENV==='h5'){
      await h5Wx.getConfig()
    }
      const isLogin = await user.checkLogin()
      if(!isLogin){
          Taro.showToast({
              title: '你还未登录，请登录',
              icon: 'none',
          })
          const timer = setTimeout(() => {
              clearTimeout(timer)
              Taro.switchTab({ url: '/pages/my/index/index' })
          }, 1500)
          return
      }
      const {orderId} = Taro.getCurrentInstance().router.params
      if(!orderId){
          Taro.showToast({ title: '参数错误', icon: 'none'})
          const timer = setTimeout(() => {
              clearTimeout(timer)
              Taro.navigateBack({
                  delta: 1
              })
          }, 1500);
      }
      Taro.showLoading({title: '加载中...'})
      const orderInfo = await newHttp.catchGet<OrderDetail>(NEW_GET_ORDER_DETAIL, {orderId})
      if(orderInfo){
        if(orderInfo.category == 6 || orderInfo.category == 7){
          this.tabs = [{title: '订单详情'},{title: '核验码'}]
        }
        if(orderInfo.category == 7 && orderInfo.show_fx_code !== 1){
          this.tabs = [{title: '订单详情'}]
        }
      }
      if(orderInfo.assembling_place){
        this.setState({
          assembling_place_list:JSON.parse(orderInfo.assembling_place)
        })
      }
      let orderTicket: any = ''
      if(orderInfo.category === 7){
       const lianOrderTicket = await newHttp.catchPost(LIAN_ORDER_TICKET+orderId)
        orderTicket = lianOrderTicket.tickets
        this.setState({qrcodeimg:orderTicket[0].qrcode})
      } else {
        orderTicket = await newHttp.catchGet<TicketItem[]>(NEW_GET_ORDER_TICKET, {orderId})

      }
      let rebateInfo: RebateInfo[] = [];
      let url = '';
      const logList = await newHttp.catchGet<LogList[]>(NEW_GET_ORDER_CHECKLOG, {orderId})
      this.setState({logList})
      if(orderInfo.category == 7){
       url = '/common/limited/localdetail?locationId=' + orderInfo.locationId + '&productId=' + orderInfo.productId;
      } else {
        if(orderInfo) {
          url = `/common/${goodsType[convert2CamelCase(orderInfo.goodsType)]}/detail?itemId=${orderInfo.guuid || ''}`;
          const res = await http.get<RebateInfo[]>(REBATE_INFO, {orderId: orderInfo.id})
          if(res) {
            rebateInfo = res
          }
        }
      }

      this.setState({ orderInfo, orderTicket,rebateInfo, goodDetailUrl: url },()=>{
        //console.log(this.state.orderTicket.length)
        if(this.state.orderInfo.category !== 7)   this.getWxQrcode()
      })
      setTimeout(() => {
          Taro.hideLoading()
      }, 100)
  }
  copy() {
      if(this.state.orderInfo){
          try{
              Taro.setClipboardData({
                  data: this.state.orderInfo.order_num
              })
            if(process.env.TARO_ENV==='h5'){
              Taro.showToast({ title: '复制成功'})
            }
          } catch (e) {
              Taro.showToast({ title: '复制失败'})
          }
      } else {
          Taro.showToast({ title: '复制失败'})
      }

  }
  copystr() {
      try{
        Taro.setClipboardData({
          data:this.state.orderInfo.linkman.split("/")[1]
        })
        if(process.env.TARO_ENV==='h5'){
          Taro.showToast({ title: '复制成功'})
        }
      } catch (e) {
        Taro.showToast({ title: '复制失败'})
      }
  }
  async getWxQrcode () {
      const orderId = this.state.orderInfo && this.state.orderInfo.id
    if(platform.info.checkStyleMini){
      if(platform.info.checkStyleMini>0){
        if(platform.info.checkStyleMini>=1 && platform.info.checkStyleMini!=2){
          Taro.request({
            url: http.url(GET_PCODE),
            data: {orderId},
            method: 'POST',
            header: await http.getHeader({'Content-Type': 'application/x-www-form-urlencoded'})
          }).then(res => {
            if(res.data.orderWxPcode){
              this.setState({
                pcodeimg:res.data.orderWxPcode
              })
            }
          })
        }
        if(platform.info.checkStyleMini>=2){
          // Taro.request({
          //   url: http.url(GET_QRCODE),
          //   data: {orderId},
          //   responseType: 'arraybuffer',
          //   method: 'POST',
          //   header:  await http.getHeader({'Content-Type': 'application/x-www-form-urlencoded'})
          // }).then(res => {
          //   let base64 = ''
          //   if(res.statusCode === 200) {
          //     base64 = Taro.arrayBufferToBase64(res.data)
          //     this.setState({
          //       qrcodeimg:'data:image/png;base64,' + base64
          //     })
          //   }
          //   // Taro.previewImage({
          //   //     current: '',
          //   //     urls: ['data:image/png;base64,' + base64]
          //   // })
          // })
          const qrCode = this.state.orderInfo.qrCode
          if(qrCode){
            this.setState({
              qrcodeimg:qrCode
            },()=>{
            })
          }

        }
      }
    }

  }
  handleClickGroup () {
    const openGroup=this.state.openGroup
    this.setState({
      openGroup: !openGroup
    })
  }
  handleAssembling () {
    const openAssembling=this.state.openAssembling
    this.setState({
      openAssembling: !openAssembling
    })
  }
  onCopy(str){
    try{
      Taro.setClipboardData({
        data: str
      })
      if(process.env.TARO_ENV==='h5'){
        Taro.showToast({ title: '复制成功'})
      }
    } catch (e) {
      Taro.showToast({ title: '复制失败'})
    }
  }
  async showCode(item){
    if(item.code_type==2){
      Taro.previewImage({
        current: item.ticket, // 当前显示图片的http链接
        urls: [item.ticket] // 需要预览的图片http链接列表
      })
    }else{
      this.onCopy(item.ticket)
    }
  }
  calendarClose(){
    this.setState({showCalendar:false})
  }
  showImg(current){
    Taro.previewImage({
      current,
      urls: [current]
    })
  }
  couponOpen(){
    const coupon=this.state.coupon
    this.setState({
      coupon:!coupon
    })
  }
  render() {
      const { showCalendar,tabsIndex, orderInfo, rebateInfo, goodDetailUrl,orderTicket, qrcodeimg, pcodeimg, logList,canvasId,openGroup,openAssembling,assembling_place_list,coupon} = this.state
      if(!orderInfo) {
          return
      }
      return (
          <View className='dist-order-root'>
            <GzhAuth />
              <AtTabs tabList={this.tabs} current={tabsIndex} onClick={this.tabsChange.bind(this)}>
                  <AtTabsPane current={tabsIndex} index={0}>
                      <View className='head'>
                          <View className='title'>订单号: <AtTag circle type='primary' size='small'>点击可复制</AtTag></View>
                          <View className={`no ${process.env.TARO_ENV}-no`} onClick={this.copy.bind(this)}>{orderInfo && orderInfo.order_num}
                            {orderInfo.tickets_check_status != 2 && <View className='back-pay'>
                              {(orderInfo && orderInfo.order_status == 90 && orderInfo && orderInfo.is_allow_refund == 1) &&
                              <View className='text'>退款处理中</View>}
                            </View>
                            }
                          </View>
                        { orderInfo.status=="已退款" && orderInfo.refund_type!=undefined && <View className={`red ${process.env.TARO_ENV}-red`}>
                          已退款退至{orderInfo.refund_type==0?'微信':(orderInfo.refund_type==1?'余额账户':(orderInfo.refund_type==2?'授信账户':'串货来源方供应商账户'))}，请注意查收~
                        </View>}
                      </View>
                      <View className='content'>
                          <View className='item'><View className='title'>订单状态:</View><View className='text'>{orderInfo && orderInfo.status}</View></View>
                          <View className='item'><View className='title'>商品名称:</View><View className='text'>{orderInfo && orderInfo.name}</View></View>
                        {orderInfo && orderInfo.meals && orderInfo.meals.length>0 &&  <View className='group' onClick={this.handleClickGroup.bind(this)}><View className='group-title'><Text>套餐包含</Text> <AtIcon value={openGroup?'chevron-down':'chevron-right'} size='15' color='#ccc'></AtIcon></View></View>}
                        {assembling_place_list && assembling_place_list.length>0 && <View className='group' onClick={this.handleAssembling.bind(this)}><View className='group-title'><Text>集结地点</Text> <AtIcon value={openAssembling?'chevron-down':'chevron-right'} size='15' color='#ccc'></AtIcon></View></View>}
                        {orderInfo.buy_date && orderInfo.goodsType!='product' && !orderInfo.valid_appointed_day && <View className='item'><View className='title'>可用日期:</View><View className='text'>{orderInfo && orderInfo.buy_date}</View></View>}
                        {orderInfo.buy_date && orderInfo.goodsType!='product' && !!orderInfo.valid_appointed_day && <View className='item'><View className='title'>可用日期:</View><View onClick={()=>{ this.setState({showCalendar:true}) }} className='text'>查看</View></View>}
                        {orderInfo.validTimeMsg && orderInfo.goodsType!='product' && <View className='item'><View className='title'>可用时间:</View><View className='text'>{orderInfo && orderInfo.validTimeMsg}</View></View>}
                        {orderInfo && orderInfo.unit_fee && orderInfo.pay_type!=4 && <View className='item'><View className='title'>商品单价:</View><View className='text'>¥{orderInfo && orderInfo.unit_fee}</View></View>}
                          <View className='item'><View className='title'>购买数量:</View><View className='text'>{orderInfo && orderInfo.buy_amount}</View></View>
                          <View className='item'><View className='title'>购买人:</View><View className='text'>{orderInfo && orderInfo.nick_name}</View></View>
                          {orderInfo && orderInfo.linkman && <Block>
                            <View className='item'><View className='title'>接收人姓名:</View><View className='text'>{orderInfo.linkman.split("/")[0]}</View></View>
                            {orderInfo.linkman.split("/")[1] && <View className='item'><View className='title'>接收人身份证:</View><View className='text'><Text onClick={this.copystr.bind(this)}>复制</Text>{orderInfo.linkman.split("/")[1]}</View></View>}
                          </Block>}

                          <View className='item'><View className='title'>接收人手机:</View><View className='text'>{orderInfo && orderInfo.phone}</View></View>
                          {orderInfo && orderInfo.address && <View className='item'><View className='title'>接收人地址:</View><View className='text'>{orderInfo && orderInfo.address}</View></View>}
                        {orderInfo && orderInfo.defined_img && <View className='group-title' onClick={this.showImg.bind(this,orderInfo.defined_img)}><Text>图片:</Text><AtIcon value='chevron-right' size='15' color='#ccc'></AtIcon></View>}
                        {orderInfo && orderInfo.remark && <View className='item'><View className='title'>备注:</View><View className='text'>{orderInfo && orderInfo.remark}</View></View>}
                          {orderInfo.pay_type!=4 && <View className='item'><View className='title'>订单金额:</View><View className='text'>¥{orderInfo && orderInfo.total_fee}</View></View>}
                        {orderInfo.coupon_discount_money && <View className='item'><View className='title'>优惠券抵扣:</View><View className='text'>¥{orderInfo && orderInfo.coupon_discount_money}</View></View>}
                        {orderInfo && (orderInfo.status=="已付款" || orderInfo.status=="已完成") && orderInfo.pay_type!=4 && <View className='item'><View className='title'>支付方式:</View><View className='text'>{orderInfo.useAccountPay_name}</View></View>}
                        {orderInfo && orderInfo.coupon_nums && orderInfo.coupon_nums.length>0 && <View className='group' onClick={this.couponOpen.bind(this)}><View className='group-title'>兑换码:<View className='text'>{orderInfo.coupon_nums[0]}{orderInfo.coupon_nums.length>1 && <AtIcon value='chevron-right' size='15' color='#ccc'></AtIcon>}</View></View></View>}

                        {orderInfo && orderInfo.offpay_date && <View className='item'><View className='title'>支付时间:</View><View className='text'>{orderInfo && orderInfo.offpay_date}</View></View>}
                        {orderInfo && orderInfo.mode_distribution && <View className='item'><View className='title'>配送方式:</View><View className='text'>{orderInfo && orderInfo.mode_distribution}</View></View>}
                          {orderInfo && orderInfo.pay_notice_mark && <View className='item'><View className='title'>产品备注:</View><View className='text'>{orderInfo && orderInfo.pay_notice_mark}</View></View>}
                        {orderInfo && orderInfo.site_remark_for_customer && <View className='item'><View className='title'>其他信息:</View><View className='text'>{orderInfo && orderInfo.site_remark_for_customer}</View></View>}
                        {orderInfo && orderInfo.pay_source_name && <View className='item'><View className='title'>订单来源:</View><View className='text'>{orderInfo && orderInfo.pay_source_name}</View></View>}
                      </View>

                  </AtTabsPane>
                {orderInfo.category!==7&&<AtTabsPane current={tabsIndex} index={1}>
                      {rebateInfo.length> 0 && rebateInfo.map(item => <View className='ticket-num' key={item.id}>
                              <View>{item.first_brokerage?'上级佣金':'佣金'}</View>
                              <View className='num'>{item.amount}</View>
                      </View>)}
                  </AtTabsPane>}
                  <AtTabsPane current={tabsIndex} index={orderInfo.category===7?1:2}>
                  {orderTicket && orderTicket.length === 0 && <View className='sms-box'>
                    <View className='sms'>
                      请以收到的短信通知为准
                    </View>
                  </View>}
                  {!orderTicket && <View className='sms-box'>
                    <View className='sms'>
                      请以收到的短信通知为准
                    </View>
                  </View>}

                  <View className='qrbox'>
                    {orderTicket && orderTicket.length > 0 && <View className='code-box'>{pcodeimg && <Image className='qrimg' src={pcodeimg}></Image>}{qrcodeimg && <Image className='qrimg' src={BASE_URL + GET_IMG + qrcodeimg}></Image>}</View>}

                    {orderTicket && orderTicket.length > 0 && orderTicket.map((item,index) => <Block key={index}>
                      <View className='ticket-num'>
                        <View>验证码</View>
                        <View className='num'>{item.ticket}</View>
                      </View>
                      <View className='ticket-info'>
                        {item.valid_date_start && item.valid_date_end && <View className='info-item'>
                          <View>有效期</View>
                          <View>{item.valid_date_start} 至 {item.valid_date_end}</View>
                        </View>}
                        <View className='info-item'>
                          <View>状态</View>
                          {orderInfo.category!==7?<View>{item.can_check_num && <Text>{item.is_use>1 && item.is_use<5 ? '已过期': '未使用'}{item.can_check_num}张</Text>}{ item.used_check_num && <Text>已使用{item.used_check_num}张</Text>}</View>
                          :<View>{Number(item.channelStatus) === 0 && <Text>未支付</Text>}{Number(item.channelStatus) === 1 && <Text>已付款</Text>}{Number(item.channelStatus) === 3 && <Text>已核销</Text>}{Number(item.channelStatus) >= 5 && <Text>已退款</Text>}</View>}

                        </View>
                        {item.use_date && <View className='info-item'>
                          <View>使用日期</View>
                          <View>{item.use_date}</View>
                        </View>}
                      </View>
                    </Block>)}
                  </View>
                  {logList.length>0 &&
                  <View className='log'>
                    <View className='log-title'>
                      使用记录
                    </View>
                    {logList.map((item,index)=>
                      <View className='log-item' key={index}>
                        <View className='log-date'>{item.use_date}<Text>{item.check_num}张</Text></View>
                      </View>
                    )}

                  </View>
                  }
                </AtTabsPane>
              </AtTabs>
              <Navigator className='back-index' url='/pages/index/index' openType='switchTab'><AtButton type='secondary'>回到首页</AtButton></Navigator>
              <Navigator className='back-index' url={goodDetailUrl} ><AtButton type='secondary'>查看商品</AtButton></Navigator>
            {orderInfo && orderInfo.meals && orderInfo.meals.length>0 &&<AtFloatLayout isOpened={openGroup} title='套餐包含' onClose={this.handleClickGroup.bind(this)} scrollY>
              {orderInfo.meals.map((val,i)=>
                <View className='group-item' key={i}>
                  <View className='group-name'>
                    <View className='group-product'><Text>{val.product_name}</Text><Text className='group-num'>x{val.buy_amount}</Text></View>
                    <View className='group-company'>{val.company}</View>
                  </View>

                </View>
              )}
            </AtFloatLayout>}
            {assembling_place_list && assembling_place_list.length>0 &&<AtFloatLayout isOpened={openAssembling} title='集合地点' onClose={this.handleAssembling.bind(this)} scrollY>
              {assembling_place_list.map((val,i)=>
                <View className='group-item' key={i}>
                  <View className='group-name'>
                    <View className='group-product'><Text>{val.assembling_place}</Text></View>
                  </View>
                </View>
              )}
            </AtFloatLayout>}

            {orderInfo && orderInfo.coupon_nums && orderInfo.coupon_nums.length>1 &&<AtFloatLayout isOpened={coupon} title='兑换码' onClose={this.couponOpen.bind(this)} scrollY>
              {orderInfo.coupon_nums.map((val,i)=>
                <View className='group-item' key={i}>
                  <View className='group-name'>
                    <View className='group-product'><Text>兑换码：</Text><Text className='group-num'>x{val}</Text></View>
                  </View>

                </View>
              )}
            </AtFloatLayout>}
            <AtFloatLayout isOpened={showCalendar} title='有效期' onClose={this.calendarClose.bind(this)}>
              <AtCalendar validDates={orderInfo.valid_appointed_day} />
            </AtFloatLayout>
          </View>

      )
  }
}
